package com.baizhi.service.impl;

import com.baizhi.service.UserService;
import com.baizhi.service.UserThreadService;
import com.baizhi.util.ThreadPollUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

@Service
public class UserThreadServiceImpl implements UserThreadService {
    @Autowired
    private UserService userService;
    private Logger logger= LoggerFactory.getLogger(UserThreadServiceImpl.class);
    @Override
    public Map selectAllCountThread() throws InterruptedException {
        Map map=new HashMap();
        //创建计数器
        CountDownLatch countDownLatch=new CountDownLatch(3);
        logger.debug("创建三个线程任务");
        /**
         *   开启三个线程任务
         *  1.查询男女比例线程任务
         */
        ThreadPollUtil.executor.execute(new Runnable() {
            @Override
            public void run() {
                /**
                 * 查询男女比例
                 */
                List<Map> maps=userService.selectCountBySex();
                map.put("sex",maps);
                countDownLatch.countDown();
            }
        });
        /**
         * 2.查询最近三个月注册量的线程任务
         */
        ThreadPollUtil.executor.execute(new Runnable() {
            @Override
            public void run() {
                /**
                 * 查询注册量
                 */
                Map map1=userService.showAll();
                map.put("count",map1);

                /**
                 * 计数器减一
                 */
                countDownLatch.countDown();
            }
        });
        /**
         *  3.查询全国每个省的人数线程任务
         */
        ThreadPollUtil.executor.execute(new Runnable() {
            @Override
            public void run() {
                List<Map> maps = userService.selectCountByProvince();
                map.put("province",maps);
                countDownLatch.countDown();
            }
        });
        /**
         * 使用wait方法让主线程等待子线程执行结束
         */
        countDownLatch.await();
        return map;
    }
}
